package com.musiklegal;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.musiklegal.BannerParser.BannerData;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MyD extends Activity implements Runnable {

	public final static int REPEAT_ALL = 1, REPEAT_OFF = 0, REPEAT_ONE = 2;
	public final static boolean SHUFFLE_ON = true, SHUFFLE_OFF = false;
	final String[] menu = { Settings.info, Settings.del, Settings.playlist, Settings.deal };
	boolean isconnected = false;
	List<SongD> hasil;
	List<SongD> cari;
	ListView list;
	Button search, prev, play, next/* ,stop */, repeat, shuffle;
	SeekBar timeBar;
	TextView timeText, status;
	int  duration, elapse;
	static int modeRepeat;
	SongD nextSong;
	static SongD currentSong;
	boolean  close, replayed, prepared, firstSong;
	static boolean isInited, paused ,shuffling;
	static MediaPlayer player;
	EditText srch;
	MusicAdapter ma;
	Banding banding;
	Thread t;
	Random rand;
	Handler h;
	AlertDialog.Builder alert;
	Toast to;
	Timer time;
	SongD sd;
	WebView wv;
	static String debug;
	ImageView iv;

	public void onResume() {
		super.onResume();
		
			new Thread(new Runnable(){

				public void run() {
					if(MusikLegal.log==null)
						MusikLegal.log = PlaylistSender.loadLog();
					if(MusikLegal.internet(getApplicationContext())&&MusikLegal.log!=null&&MusikLegal.log.listSong.size()>0)
		        	{
		        		try {
							MusikLegal.log.send();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		        	}
					
				}}).start();
			
			
			

		
	}

	private synchronized void init() {
		setContentView(R.layout.myd);
		if (player == null)
			player = new MediaPlayer();
		MainMenu.setStatus(this);
		hasil = new ArrayList<SongD>();
		
		duration = 0;
		elapse = 0;
		// shuffling =false;
		// paused=false;
		close = false;
		// prepared=false;
		// replayed=false;
		firstSong = true;
		rand = new Random();
		search = (Button) findViewById(R.id.srchdlbut);
		srch = (EditText) findViewById(R.id.srchdl);
		list = (ListView) findViewById(R.id.PhoneMusicList);
		prev = (Button) findViewById(R.id.prev);
		play = (Button) findViewById(R.id.play);
		next = (Button) findViewById(R.id.next);
		cari = new ArrayList<SongD>();
		repeat = (Button) findViewById(R.id.repeat);
		switch (modeRepeat) {
		case 0:
			repeat.setBackgroundResource(R.drawable.rpoff);
			break;
		case 1:
			repeat.setBackgroundResource(R.drawable.rpall);
			break;
		case 2:
			repeat.setBackgroundResource(R.drawable.rpone);
			break;
		}
		shuffle = (Button) findViewById(R.id.shuffle);
		if (shuffling)
			// shuffle.setText("shuf ON");
			shuffle.setBackgroundResource(R.drawable.shon);
		else
			shuffle.setBackgroundResource(R.drawable.shoff);
		timeText = (TextView) findViewById(R.id.timeelapse);
		timeBar = (SeekBar) findViewById(R.id.timeBar);
		status = (TextView) findViewById(R.id.status);
		iv  = (ImageView) findViewById(R.id.banner);

		new Thread(new Runnable() {

			public void run() {
				try {

					MyD.loadBanner(MyD.this, iv,h);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (NullPointerException e)
				{
					e.printStackTrace();
				}

			}
		}).start();

		alert = new AlertDialog.Builder(this);
		h = new Handler();
		banding = new Banding();
		hasil = MusikLegal.listDownload;
		sortList();
		ma = new MusicAdapter(this, hasil);
		
		list.setAdapter(ma);

		list.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {

				alert.setTitle(Settings.joption);
				alert.setIcon(R.drawable.oc2);
				alert.setItems(menu, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {

						switch (item) {
						case 0:
							
							TrackInfo.item = (SongD) list
									.getItemAtPosition(arg2);
							TrackInfo.fromCatalogue = false;
							TrackInfo.isCatalogue = true;
							startActivity(new Intent(getApplicationContext(),
									TrackInfo.class));
							break;
						case 1:
							SongD it = (SongD) list.getItemAtPosition(arg2);
							if (currentSong != null && currentSong.equals(it)) {
								stop();

								currentSong = null;
								isInited = false;
								paused = false;
							}
							removeItem(it);
							Toast.makeText(getApplicationContext(),
									"Song Deleted", Toast.LENGTH_SHORT).show();
							list.invalidateViews();
							break;
						case 2:
							sd = hasil.get(arg2);
							if (addToPlaylist(sd))
								Toast.makeText(getApplicationContext(),
										"Added To MyPlayList ",
										Toast.LENGTH_SHORT).show();
							else
								Toast.makeText(getApplicationContext(),
										"Already Added to MyPlayList ",
										Toast.LENGTH_SHORT).show();
							break;
						
						case 3:
							
                				stop();
                				MyD.currentSong=null;
                				MyD.isInited=false;
                				MyD.paused= false;
                			
                				
                			removeAll();
                			Toast.makeText(getApplicationContext(), "All Songs in PlayList are deleted", Toast.LENGTH_SHORT).show();
                			list.invalidateViews();
							
							
						}

					}
				});
				alert.setCancelable(true);
				alert.create();
				alert.show();

				return false;

			}
		});

		repeat.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				changeMode();
				switch (modeRepeat) {
				case 0:
					repeat.setBackgroundResource(R.drawable.rpoff);
					break;
				case 1:
					repeat.setBackgroundResource(R.drawable.rpall);
					break;
				case 2:
					repeat.setBackgroundResource(R.drawable.rpone);
					break;
				}

			}
		});

		shuffle.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				changeShuffle();

				if (shuffling)
					// shuffle.setText("shuf ON");
					shuffle.setBackgroundResource(R.drawable.shon);
				else
					shuffle.setBackgroundResource(R.drawable.shoff);

			}
		});

		player.setOnErrorListener(new OnErrorListener() {

			public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
				if (currentSong != null) {
					MyD.currentSong.isplaying = false;
					MyD.isInited = false;
					MyD.currentSong = null;
				}
				player.reset();
				return true;
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {

				SongD song = (SongD) list.getItemAtPosition(position);
				if (!song.isplaying) {
					if (currentSong != null)
						currentSong.isplaying = false;

					currentSong = song;
					paused = false;
					stop();
					if(!MusikLegal.on )
					{
						if((currentSong!=null&&MusikLegal.db.checkSong(currentSong.idRing)))
						{
							//Toast.makeText(getApplicationContext(), "o1k", 1).show();
							play();
						}
						else if((currentSong!=null&&!MusikLegal.db.checkSong(currentSong.idRing)))
						{
							//Toast.makeText(getApplicationContext(), "ok", 1).show();
							
							final String uname = MusikLegal.mPreferences.getString("UserName", "");
							final String pass = MusikLegal.mPreferences.getString("PassWord", "");
							
								// TODO Auto-generated method stub
							AlertDialog.Builder dialog = new AlertDialog.Builder(MyD.this);
					    	dialog.setTitle(Settings.jmulaisubs);
					    	dialog.setMessage(Settings.warning);
					    	//dialog.setCancelable(false);
					    	dialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){

								

								public void onClick(DialogInterface arg0,
										int arg1) {
									
									startSubscription(uname,pass,MyD.this);
									
								}});
					    	dialog.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									
								}
							});
					    	dialog.create();
					    	dialog.setIcon(R.drawable.oc2);
					        dialog.show();
					        
							
							//	startSubscription(uname,pass,MyD.this);	
								
							
							
						}
					}
					else
						play();
					
				}
			}
		});

		search.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				cari.clear();
				for (SongD o : MusikLegal.listDownload) {
					if (o.title.toLowerCase().contains(
							srch.getText().toString().toLowerCase())
							|| o.artist.toLowerCase().contains(
									srch.getText().toString().toLowerCase()))
						cari.add(o);
				}

				ma.list = cari;

				TimerTask task = new TimerTask() {

					@Override
					public void run() {
						ma.list = hasil;
						h.post(new Runnable() {

							public void run() {
								list.invalidateViews();
								time.cancel();

							}
						});

					}
				};
				time = new Timer();
				time.schedule(task, 5000);
				list.invalidateViews();
			}
		});

		timeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {

				if (!close && fromUser && isInited) {
					player.seekTo(progress);
				}

			}

			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});

		player.setOnCompletionListener(new OnCompletionListener() {

			public void onCompletion(MediaPlayer mp) {
				if (hasil.size() > 0) {
					currentSong.isplaying = false;
					if (modeRepeat == 2)
						replay();
					else if (hasil.indexOf(currentSong) < hasil.size() - 1
							|| shuffling || modeRepeat == MyD.REPEAT_ALL)
						next(true);
					else {
						stop();
						play.setBackgroundResource(R.drawable.play);
						isInited = true;
					}
				}

				list.invalidateViews();

			}
		});

		next.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (hasil.size() > 0)
					next(true);
			}
		});

		prev.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (hasil.size() > 0)
					next(false);

			}
		});

		play.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (hasil.size() > 0)
					play();
			}
		});
		list.invalidateViews();
	}

	void replay() {

		player.reset();
		if (MusikLegal.on || MusikLegal.db.checkSong(currentSong.idRing)) {
			try {
				player.setDataSource(MusikLegal.mainFolder + "/temp");
				player.prepare();
			} catch (IllegalStateException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			timeBar.setProgress(0);
			paused = true;
			decodeTimeElapse(0, duration);
			player.start();
			currentSong.isplaying=true;
			if (!MusikLegal.on) {
				MusikLegal.db.substract(currentSong.idRing);
				Toast.makeText(
						getApplicationContext(),
						MusikLegal.db.getCount(currentSong.idRing)
								+ " times remaining", Toast.LENGTH_SHORT)
						.show();
			} else {
				new Thread(new Runnable() {

					public void run() {
						try {
							
							if(MusikLegal.internet(getApplicationContext()))
							PlaylistSender.sendSong(new File(
									MyD.currentSong.location),
									getApplicationContext());
							else
								MusikLegal.log.addSong(new File(MyD.currentSong.location), getApplicationContext());
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}).start();

			}
			play.setBackgroundResource(R.drawable.pausebut);
			replayed = true;
		}

	}

	void stop() {
		player.reset();
		currentSong.isplaying = false;
		isInited = false;
		timeBar.setProgress(0);
		decodeTimeElapse(0, duration);
		list.invalidateViews();
		play.setBackgroundResource(R.drawable.play);

		// timeBar.setEnabled(false);
	}

	void next(boolean isForward) {
		currentSong.isplaying = false;
		player.reset();
		isInited = false;
		paused = false;
		if (isForward) {

			if (!shuffling) {
				if ((hasil.indexOf(currentSong) < hasil.size() - 1
						|| modeRepeat == 1)) {
					getNextSong(isForward);
					currentSong = nextSong;

					play();
					paused = false;
				} 
				else
				{
					stop();
				}
			} else {
				if(hasil.size()>1)
				{	getNextSong(isForward);
				MyD.currentSong=nextSong;
				
					
					
					play();
					MyD.paused=false;
				}
				else
				{
					stop();
				}
			}
		} else {
			if (!shuffling) {
				if (hasil.indexOf(currentSong) > 0 || modeRepeat == 1) {
					getNextSong(isForward);
					currentSong = nextSong;

					// player.reset();

					play();
					paused = false;

				} else {
					stop();
				}
			} else {
				if(hasil.size()>1)
				{	getNextSong(isForward);
				MyD.currentSong=nextSong;
				
					
					
					play();
					MyD.paused=false;
				}
				else
				{
					stop();
				}

			}
		}

	}

	void changeMode() {
		modeRepeat = (modeRepeat + 1) % 3;
		if (hasil.size() != 0)
			getNextSong(true);
	}

	void changeShuffle() {

		shuffling = !shuffling;
		if (hasil.size() != 0)
			getNextSong(true);
	}

	public void onDestroy() {
		close = true;
		
		System.gc();
		ma.list = hasil;
		if(ma!=null)
			ma.clear();
		super.onDestroy();
	}

	void setEnabledAll(boolean enable) {
		prev.setEnabled(enable);
		play.setEnabled(enable);
		next.setEnabled(enable);

	}

	public void getNextSong(boolean isForward) {
		if (!shuffling) {
			if (isForward) {
				if (modeRepeat == 0 || modeRepeat==2) {
					if (hasil.indexOf(currentSong) == hasil.size() - 1) {
						return;
					} else {
						nextSong = hasil.get((hasil.indexOf(currentSong) + 1));
						return;
					}
				} else if (modeRepeat == 1) {
					nextSong = hasil.get((hasil.indexOf(currentSong) + 1)
							% hasil.size());
					return;
				}
			} else {
				if (modeRepeat == 0 || modeRepeat == 2) {
					if (hasil.indexOf(currentSong) <= 0) {
						return;
					} else {
						nextSong = hasil.get((hasil.indexOf(currentSong) - 1));
						return;
					}
				} else if (modeRepeat == 1) {

					nextSong = hasil
							.get((hasil.indexOf(currentSong) - 1 + hasil.size())
									% hasil.size());
					return;
				}

			}

		} else {
			
			if(hasil.size()>1)
			nextSong = hasil.get(getRandom());
		}

		return;
	}

	int getRandom() {
		int r = rand.nextInt(hasil.size());
		if (r == hasil.indexOf(currentSong))
			return getRandom();
		else
			return r;
	}

	void decodeTimeElapse(int elapse, int duration) {
		int minute = elapse / 60000;
		int second = (elapse / 1000) % 60;

		StringBuffer time = new StringBuffer(((minute < 10) ? ("0" + minute)
				: (minute + ""))
				+ ":"
				+ ((second < 10) ? ("0" + second) : (second + "")) + "/");
		minute = duration / 60000;
		second = (duration / 1000) % 60;
		time.append(((minute < 10) ? ("0" + minute) : (minute + "")) + ":"
				+ ((second < 10) ? ("0" + second) : (second + "")));
		timeText.setText(time.toString());
	}

	void play() {

		try {
			if (player.isPlaying()) {
				player.pause();
				if (!replayed) {
					play.setBackgroundResource(R.drawable.play);
				} else
					replayed = false;
				paused = true;
			} else {
				if (!paused) {

					// Toast.makeText(getApplicationContext(),
					// currentSong.location, Toast.LENGTH_SHORT).show();
					if (MusikLegal.on || (currentSong != null && MusikLegal.db
									.checkSong(currentSong.idRing))) 
					{
						player.reset();
						String p = decodeG3n(currentSong);
						player.setDataSource(p);
						player.prepare();
						timeBar.setMax(player.getDuration());
						timeBar.setProgress(0);
						status.setText(currentSong.title + " - "
								+ currentSong.artist);
						currentSong.isplaying = true;
						duration = player.getDuration();
						decodeTimeElapse(0, duration);
						t = new Thread(this);
						player.start();
						t.start();
						play.setBackgroundResource(R.drawable.pausebut);
						isInited = true;
						firstSong = false;
						list.invalidateViews();
						if (!MusikLegal.on) {
							MusikLegal.db.substract(currentSong.idRing);
							Toast.makeText(
									getApplicationContext(),
									MusikLegal.db.getCount(currentSong.idRing)
											+ ((MusikLegal.db.getCount(currentSong.idRing)<=1)?" time":" times")+" remaining",
									Toast.LENGTH_SHORT).show();
						} else {

							new Thread(new Runnable() {

								public void run() {
									try {
										if(MusikLegal.internet(getApplicationContext()))
										PlaylistSender.sendSong(new File(
												MyD.currentSong.location),
												getApplicationContext());
										else
											MusikLegal.log.addSong(new File(MyD.currentSong.location), getApplicationContext());
									} catch (IllegalStateException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (SAXException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (ParserConfigurationException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}
							}).start();
						}
					}
					 else 
					 {
						Toast.makeText(getApplicationContext(), Settings.expd,
								Toast.LENGTH_SHORT).show();
						stop();
					}
				} else if (!firstSong || paused) 
				{
					
					player.start();
					status.setText(currentSong.title+" - "+currentSong.artist);
					play.setBackgroundResource(R.drawable.pausebut);
					t = new Thread(this);
					t.start();
					paused = false;
				}

			}

		} catch (IllegalArgumentException e) {
			// Toast.makeText(getApplicationContext(), e.getMessage(),
			// Toast.LENGTH_SHORT).show();
			player.reset();
			status.setText("ilegal argument");
			paused = false;
			decodeTimeElapse(0, duration);
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// Toast.makeText(getApplicationContext(), e.getMessage(),
			// Toast.LENGTH_SHORT).show();
			player.reset();
			status.setText("illegalstate");
			paused = false;
			decodeTimeElapse(0, duration);
			e.printStackTrace();
		} catch (IOException e) {
			// Toast.makeText(getApplicationContext(), e.getMessage(),
			// Toast.LENGTH_SHORT).show();
			player.reset();
			status.setText("ioexception");
			paused = false;
			decodeTimeElapse(0, duration);
			e.printStackTrace();
		}
	}

	static class Banding implements Comparator<SongD> {
		public int compare(SongD arg0, SongD arg1) {

			if (arg0.downloaded < arg1.downloaded)
				return 1;
			else if (arg1.downloaded < arg0.downloaded)
				return -1;
			else
				return 0;
		}
	}

	void sortList() {
		Collections.sort(hasil, banding);
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new Thread(new Runnable(){

			public void run() {
				if(MusikLegal.internet(getApplicationContext()))
				{
					if(MusikLegal.log==null)
						MusikLegal.log=PlaylistSender.loadLog();
					if(MusikLegal.log !=null && MusikLegal.log.listSong.size()>0)
		        	{
						
		        		try {
							MusikLegal.log.send();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		        	}
				}
				
			}}).start();
		
		// if(MusikLegal.internet(getApplicationContext()))
		{

			init();
			if (isInited) {
				
				duration = player.getDuration();
				timeBar.setMax(duration);
				status.setText(currentSong.title + " - " + currentSong.artist);
				decodeTimeElapse(player.getCurrentPosition(), duration);
				getNextSong(true);
				new Thread(this).start();
			} else if (hasil.size() != 0) {
				currentSong = hasil.get(0);
			}

		}
		// else
		// {
		// AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		// alertDialog.setTitle("Error");
		// alertDialog.setMessage(Settings.gakonek);
		// alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int which) {
		// finish();
		// }
		// });
		// alertDialog.setIcon(R.drawable.oc2);
		// alertDialog.show();
		// }
	}

	String decodeG3n(SongD s) throws IOException {
		String pth = null;
		try {
			pth = decrypt(new File(s.location)).getPath();
		} catch (Exception e) {
			removeItem(s);
		}

		return pth;
	}

	synchronized void removeItem(SongD sd) {
		hasil.remove(sd);
		MusikLegal.myPlaylist.remove(sd);
		MusikLegal.dataSet.remove(sd);
		File del = new File(sd.location);
		del.delete();
		rewrite(hasil);
	}

	void rewrite(List<SongD> hasil) {

		File f = new File(MusikLegal.listD);
		BufferedWriter bw;
		try {
			bw = new BufferedWriter((new FileWriter(f)));
			Iterator<SongD> it = hasil.iterator();
			while (it.hasNext()) {
				SongD s = it.next();
				bw.write(s.toString() + "\n");
			}
			bw.flush();
			bw.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	public File decrypt(File src) throws IOException {

		File temp = new File(MusikLegal.mainFolder+"temp");
		int key = 1612;
		BufferedInputStream is = new BufferedInputStream(new FileInputStream(
				src));
		BufferedOutputStream os = new BufferedOutputStream(
				new FileOutputStream(temp));

		int c;
		int clen = 0;
		byte[] cs = new byte[(int) src.length() - 256];
		while ((c = is.read()) >= 0) {
			if (clen > 256) {
				c = (byte) ((c - 88) ^ (~((int) (key >> clen))));
				cs[clen - 256] = (byte) c;
			}
			clen++;
		}
		os.write(cs);
		is.close();
		os.flush();
		return temp;

	}

	static class MusicAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		List<SongD> list;
		Activity act;
		ImageLoader imageLoader;

		public MusicAdapter(Activity a, List<SongD> p) {
			act = a;
			list = p;
			mInflater = (LayoutInflater) a
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			imageLoader = new ImageLoader();
		}

		public int getCount() {

			return list.size();
		}

		public Object getItem(int arg0) {

			return list.get(arg0);
		}

		public long getItemId(int position) {

			return position;
		}

		class ViewHolder {
			ImageView img, playing;
			TextView text1, text2;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			View rowView = convertView;

			SongD p = list.get(position);// (SongD) getItem(position);
			ViewHolder holder;

			if (rowView == null) {

				rowView = mInflater.inflate(R.layout.view, null);

				holder = new ViewHolder();
				holder.text1 = (TextView) rowView.findViewById(R.id.TextView01);
				holder.text2 = (TextView) rowView.findViewById(R.id.TextView02);
				holder.img = (ImageView) rowView.findViewById(R.id.ImageView01);
				holder.playing = (ImageView) rowView
						.findViewById(R.id.imageView1);
				rowView.setTag(holder);
			} else {
				holder = (ViewHolder) rowView.getTag();
			}

			String uri = Uri.fromFile(
					new File(MusikLegal.albumArtFolder + p.albumid + ".jpg"))
					.toString();

			holder.text1.setText(p.title);
			holder.text2.setText(p.artist);
			holder.img.setTag(uri);
			if (p != null && p.isplaying)
				{
					holder.playing.setVisibility(ImageView.VISIBLE);
					holder.text1.setTextColor(Color.RED);
					holder.text2.setTextColor(Color.RED);
				}
			else
			{
				holder.playing.setVisibility(ImageView.INVISIBLE);
				holder.text1.setTextColor(Color.WHITE);
				holder.text2.setTextColor(Color.WHITE);
			}
			imageLoader.DisplayImage(uri, act, holder.img, p.albumid);

			return rowView;
		}
		
		public void clear()
		{
			imageLoader.clearMemory();
		}
	}

	int k;

	public void run() {

		while (!close && player.isPlaying()) {
			
			k = player.getCurrentPosition();
			timeBar.setProgress(k);
			h.post(new Runnable() {

				public void run() {
					decodeTimeElapse(k, duration);
					play.setBackgroundResource(R.drawable.pausebut);
				}
			});
			// decodeTimeElapse(k,duration);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {

			} catch (IllegalStateException e) {

			} catch (Exception e) {
			}
		}
	}


	boolean addToPlaylist(SongD aSong) {
		File s = new File(MusikLegal.playlist);
		if (!MusikLegal.myPlaylist.contains(aSong)) {
			MusikLegal.myPlaylist.add(0, aSong);

			try {

				BufferedWriter bw = new BufferedWriter(new FileWriter(s, true));
				bw.write(aSong.idRing + "\n");

				bw.flush();
				bw.close();
				return true;

			} catch (IOException e) {

				e.printStackTrace();
				return false;
			}

		} else
			return false;
	}

	private void browseTo(WebView wv, String url) {
		wv.getSettings().setJavaScriptEnabled(true);
		wv.getSettings().setPluginsEnabled(true);
		// wv.getSettings().setAppCacheEnabled(false);
		wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		wv.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {

			}
		});

		wv.setWebViewClient(new WebViewClient() {
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// Handle the error
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {

				view.loadUrl(url);

				return true;
			}

			public void onPageFinished(WebView view, String url) {

			}
		});

		wv.loadUrl(url);

	}

	static void loadBanner(final Activity c, final ImageView button,Handler h) throws IOException,
			ParserConfigurationException, SAXException, NullPointerException{
		Display d = ((WindowManager) c.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		URL addr = new URL(
				"http://secure.musiklegal.com/?action=banner&method=android_banner&width="
						+ (d.getWidth()));
		addr.openConnection();
		InputSource isrc = new InputSource(addr.openStream());
		BannerParser bp = new BannerParser();
		
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		
		
		
		xr.setContentHandler(bp);
		xr.parse(isrc);
		final BannerData bd = bp.bannerData;
		addr = new URL(bd.media);
		addr.openConnection();
		final Bitmap bitmap = BitmapFactory.decodeStream(addr.openStream());
		
		h.post(new Runnable(){

			public void run() {
				button.setVisibility(View.VISIBLE);
				button.setImageBitmap(bitmap);
				
			}});
		
		button.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				LoginWeb.urlTo = bd.address;
				c.startActivity(new Intent(c, LoginWeb.class));
				
			}});
		
		
		
		
	}
	
	String endDate;
	void startSubscription(final String uname, final String password, final Activity act)
	{
		//Toast.makeText(getApplicationContext(), "act", 1).show();
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    	dialog.setTitle(Settings.jmulaisubs);
    	dialog.setMessage(Settings.mulaisubs+MusikLegal.mPreferences.getString("Balance", "0")+Settings.mulaisubs2);
    	dialog.setCancelable(false);
    	dialog.setPositiveButton(Settings.yes, new DialogInterface.OnClickListener() {
    	public void onClick(DialogInterface dialog, int id)
    	{
    		new Thread(new Runnable(){

				public void run() {
					// TODO Auto-generated method stub
					String username =uname;
					String uid = MusikLegal.getUID(getApplicationContext());
				    String pass = password;
						
					DefaultHttpClient client = new DefaultHttpClient();
			        HttpPost httppost = new HttpPost("http://secure.musiklegal.com/subscription/start_weekly");
			        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
			        nvps.add(new BasicNameValuePair("USERNAME", username));
			        nvps.add(new BasicNameValuePair("UID", uid));
			        nvps.add(new BasicNameValuePair("PASSWORD", pass));
			 
			        try {   
			      	  	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
			            
			            httppost.setEntity(p_entity);
			            
			            HttpResponse response = client.execute(httppost);
			            HttpEntity responseEntity = response.getEntity();
			            

			            SAXParserFactory spf = SAXParserFactory.newInstance();
			            SAXParser sp = spf.newSAXParser();
			            XMLReader xr = sp.getXMLReader();
			            
			            LoginHandler myLoginHandler = new LoginHandler();
			            xr.setContentHandler(myLoginHandler);
			            xr.parse(new InputSource(responseEntity.getContent()));
			            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
			           
			           

			            
			            if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) 
			            {
			            	 SharedPreferences.Editor editor=MusikLegal.mPreferences.edit();
			                  
			            	 editor.remove("START").commit();
					              editor.remove("SubId").commit();
					              editor.remove("SubDate").commit();
					              endDate = parsedLoginDataSet.getDate();
			            	if(parsedLoginDataSet.getSiD()!=null)
		                   {
		    	            	editor.putString("SubDate", parsedLoginDataSet.getDate()).commit();
		    	            	editor.putString("START", parsedLoginDataSet.getStart()).commit();
		                       	editor.putString("SubId", parsedLoginDataSet.getSiD()).commit();
		                   }
			            	
			            	MusikLegal.on = true;
			            	
			            	MainMenu.setStatus(act);
			            	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.thank, Toast.LENGTH_SHORT).show();
									play();
								}});
			            	
			        	    
			                 
			            } else  
			            {
			            	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.error, Toast.LENGTH_SHORT).show();
								}});
			            	
			            }
			      } catch (Exception e)
			      {
			          
			      }
				
				}}).start();
    		
    	}

    	});
    	
    	dialog.setNegativeButton(Settings.no, new DialogInterface.OnClickListener() { 
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    	} });
    	dialog.create();
    	dialog.setIcon(R.drawable.oc2);
        dialog.show();
    	
    	}
	
	void removeAll()
	{
		for(SongD s :MusikLegal.dataSet)
		{
			new File(s.location).delete();
		}
		hasil.clear();
		MusikLegal.listDownload.clear();
		MusikLegal.myPlaylist.clear();
		rewrite(hasil);
	}
	
	
	}
